package Demo2;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

//循环队列判满 浪费一个空间 或者  记录元素个数 或者 设置一个变量标记是空还是满
class MyBlockingQueue {
    volatile private int[] items = new int[10];
    volatile public int size = 0;
    volatile public int tail = 0;
    volatile public int head = 0;

    synchronized public void put(int val) throws InterruptedException {
        if (size == items.length) {
            this.wait();
        }
        items[tail] = val;
        tail++;

        if (items.length == tail) {
            tail = 0;
        }
        // tail = tail % items.length;
        // 求余数不仅不直观，而且对于计算机而言不是个高效操作
        size++;
        this.notify();
    }


    synchronized public Integer take() throws InterruptedException {
        if (size == 0) {
            this.wait();
        }
        int val = items[head];
        head++;
        if (head == items.length) {
            head = 0;
        }
        size--;
        this.notify();
        return val;

    }




}
public class Thread3 {

    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue =
                new MyBlockingQueue();

    }

    public static void main1(String[] args) throws InterruptedException {


        BlockingQueue<String> blockingQueue =
                new LinkedBlockingQueue<>();
        //阻塞队列核心方法，主要有两个
        //put 入队 和 take 出队
        blockingQueue.put("hello1");
        blockingQueue.put("hello2");
        blockingQueue.put("hello3");
        blockingQueue.put("hello4");
        blockingQueue.put("hello5");

        String result = null;
        result = blockingQueue.take();
        System.out.println(result);
        result = blockingQueue.take();
        System.out.println(result);
        result = blockingQueue.take();
        System.out.println(result);
        result = blockingQueue.take();
        System.out.println(result);
        result = blockingQueue.take();
        System.out.println(result);
        result = blockingQueue.take();
        System.out.println(result);
        result = blockingQueue.take();
        System.out.println(result);


    }
}
